<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Env;

class Pay extends Home
{
    protected $noNeedLogin = ['callback'];
    protected  $PayModel;
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();

        $this->PayModel = model('Pay.Pay');
    }
    public function pay()
    {
        if ($this->request->isPost()) {
            $money = $this->request->param('money', 0, 'trim');
            $paytype = $this->request->param('paytype', 0, 'trim');
            $money = floatval($money);
            if ($money < 0) {
                $this->error('充值金额不能小于1元');
            }
            // 用户ID
            $third = json_encode(['busid' => $this->LoginUser['id']]);
            // Env 获取env文件路面的，没有再获取数据库里的 获取当前站点域名
            $url = Env::get('site.url', config('site.url'));
            // 下单地址
            $OrderUrl = $url . '/pay/index/create';
            $data = [
                'name' => '余额充值',
                'third' => $third,
                'paytype' => $paytype,
                'originalprice' => $money,
                'paypage' => 1, // 0 json 1 收银页面,
                'reurl' => 'https://jie.jied.top/home/pay/notice',
                'callbackurl' => 'https://jie.jied.top/home/pay/callback',
                'status' => '0',
                'wxcode' => $url . config('site.wxcode'),
                'zfbcode' => $url . config('site.zfbcode'),
            ];
            $result = httpRequest($OrderUrl, $data);
            echo $result;
            exit;
        }
        return $this->fetch();
    }
    // 支付完回调函数
    public function callback()
    {
        $params = $this->request->param();
        $price = isset($params['price']) ? $params['price'] : 0;
        $third = isset($params['third']) ? $params['third'] : '';
        // json字符串($third,true) true 转换数组 默认对象
        $third = json_decode($third, true);
        $busid = isset($third['busid']) ? $third['busid'] : 0;
        $paytype = isset($params['paytype']) ? $params['paytype'] : 0;
        // 支付订单id
        $payid = isset($params['id']) ? $params['id'] : 0;
        $pay = $this->PayModel->find($payid);
        
        if (!$pay) {
            return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
        }
        // 充值类型转换
        $payment = '';
        switch ($paytype) {
            case 0:
                $payment = "微信支付";
                break;
            case 1:
                $payment = "支付宝支付";
                break;
        }
        // 判断充值金额
        if ($price <= 0) {
            return json(['code' => 0, 'msg' => '充值金额为0', 'data' => null]);
        }
        $business = $this->BusinessModel->find($busid);
        if (!$business) {
            return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
        }
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();
        $updateMoney=bcadd($price,$business['money'],2);
        // 封装用户更新的数据
        $BusinessData = [
            'id' => $busid,
            'money' => $updateMoney,
        ];
        // 自定义验证器
        $validate = [
            [
                'money' => ['number', '>:0']
            ],
            [
                'money.number' => '余额必须是数字类型',
                'money.>' => '余额必须大于等于0元'
            ]
        ];
        //显式指定更新数据操作
        $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate()->save($BusinessData);
        if ($BusinessStatus === false) {
            return json(['code' => 0, 'msg' => $this->BusinessModel->getError(), 'data' => null]);
        }
        // 封装订单添加的数据
        $RecordData = [
            'total' => $price,
            'content' => "{$payment}充值了{$price}元",
            'busid' => $busid,
            'state' => '3'
        ];
        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
        if($RecordStatus === false){
            $this->BusinessModel->rollback();
            return json(['code' => 0, 'msg' => $this->RecordModel->getError(), 'data' => null]);
        }
        $this->BusinessModel->commit();
        $this->RecordModel->commit();
        return json(['code' => 1, 'msg' => '充值成功', 'data' => null]);
    }


    // 订单支付完成后跳转的网页
    public function notice()
    {
        return $this->success('支付成功', '/home/business/index');
    }
}
